package vip.denglei.company.controller.app;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaUserInfo;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.web.bind.annotation.*;
import vip.denglei.company.model.app.AppUserInfo;
import vip.denglei.company.model.app.bo.WechatLoginBO;
import vip.denglei.company.service.app.AppUserService;
import vip.denglei.company.util.HttpResult;

import javax.annotation.Resource;
import java.util.Objects;

@RestController
@RequestMapping(value = "/user")
@Slf4j
public class AppUserController {


    @Resource
    private WxMaService wxMaService;
    @Resource
    private AppUserService appUserService;

    /**
     * 小程序登录
     *
     * @param wechatLoginBO
     * @return
     */
    @PostMapping("login")
    public HttpResult login(@RequestBody WechatLoginBO wechatLoginBO) {
        log.info("AppUserController login 参数wechatLoginBO:{} ", wechatLoginBO);
//        WxMaJscode2SessionResult sessionInfo = null;

        WxMaPhoneNumberInfo wxMaPhoneNumberInfo = null;
        try {
            wxMaPhoneNumberInfo = wxMaService.getUserService().getPhoneNoInfo(wechatLoginBO.getCode());
            log.info("获取手机号码wxMaPhoneNumberInfo;{}", wxMaPhoneNumberInfo);
//            sessionInfo = wxMaService.getUserService().getSessionInfo(wechatLoginBO.getCode());
//            log.info("获取微信 sessionInfo :{} ", sessionInfo);
//            if (Objects.nonNull(sessionInfo)) {
//            wxMaPhoneNumberInfo = wxMaService.getUserService().getPhoneNoInfo(sessionInfo.getSessionKey(), wechatLoginBO.getEncryptedData(), wechatLoginBO.getIv());
//            log.info("获取手机号码wxMaPhoneNumberInfo;{}", wxMaPhoneNumberInfo);
            LambdaQueryWrapper<AppUserInfo> appUserInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            appUserInfoLambdaQueryWrapper.eq(AppUserInfo::getUserPhone, wxMaPhoneNumberInfo.getPhoneNumber());
            AppUserInfo appUserInfo = appUserService.getOne(appUserInfoLambdaQueryWrapper);
            if (Objects.nonNull(wxMaPhoneNumberInfo)) {
                if (Objects.isNull(appUserInfo)) {
                    appUserInfo = new AppUserInfo();
                    appUserInfo.setUserId(IdUtil.nanoId());
//                    appUserInfo.setUserName("测试" + appUserInfo.getUserId());
                    appUserInfo.setUserPhone(wxMaPhoneNumberInfo.getPhoneNumber());
                    appUserService.save(appUserInfo);
                }
                return HttpResult.success(appUserInfo);
            }

        } catch (WxErrorException e) {
            log.error("微信小程序登录失败");
            throw new RuntimeException(e);
        }

        return HttpResult.err("登录失败");
    }

    @PostMapping("getWxMaUserInfo ")
    public HttpResult getWxMaUserInfo(@RequestBody WechatLoginBO wechatLoginBO) {
        log.info("AppUserController getWxMaUserInfo 参数wechatLoginBO:{} ", wechatLoginBO);
        AppUserInfo appUserInfo = null;
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(wechatLoginBO.getCode());
            // 调用微信 API 获取用户的详细信息
            WxMaUserInfo userInfo = wxMaService.getUserService().getUserInfo(session.getSessionKey(), wechatLoginBO.getEncryptedData(), wechatLoginBO.getIv());
            if (ObjectUtil.isNotEmpty(userInfo)) {
                if (StrUtil.isEmpty(wechatLoginBO.getUserId())) {
                    LambdaQueryWrapper<AppUserInfo> appUserInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    appUserInfoLambdaQueryWrapper.eq(AppUserInfo::getUserPhone, wechatLoginBO.getUserId());
                    appUserInfo = appUserService.getOne(appUserInfoLambdaQueryWrapper);
                    if (ObjectUtil.isNotEmpty(appUserInfo)) {
                        appUserInfo.setUserName(userInfo.getNickName());
                        appUserInfo.setUserSex(Integer.valueOf(userInfo.getGender()));
                        appUserInfo.setAvatarUrl(userInfo.getAvatarUrl());
                    }

                }

            }
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        return HttpResult.success(appUserInfo);
    }

    /**
     * 更新用户微信openID
     *
     * @param appUserInfo
     * @return
     */

    @PutMapping("update/userOpenId")
    public HttpResult updateUserOpenId(@RequestBody AppUserInfo appUserInfo) {
        log.info("AppUserController updateUserOpenId 参数appUserInfo:{} ", appUserInfo);
        LambdaQueryWrapper<AppUserInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AppUserInfo::getUserId, appUserInfo.getUserId());
        AppUserInfo appUserInfo1 = appUserService.getOne(lambdaQueryWrapper);
        WxMaJscode2SessionResult sessionInfo = null;
        if (Objects.nonNull(appUserInfo1)) {
            try {
                sessionInfo = wxMaService.getUserService().getSessionInfo(appUserInfo.getWechatId());
                if (Objects.nonNull(sessionInfo)) {
                    appUserInfo1.setWechatId(sessionInfo.getOpenid());
                }
            } catch (WxErrorException e) {
                throw new RuntimeException(e);
            }

            appUserService.updateById(appUserInfo1);

        }
        return HttpResult.success(appUserInfo1);
    }

    @PutMapping("update/appUserInfo")
    public HttpResult updateAppUserInfo(@RequestBody AppUserInfo appUserInfo) {
        appUserService.updateById(appUserInfo);
        return HttpResult.success();
    }
}
